package zad1;

import java.util.ArrayDeque;
import java.util.Deque;

public class Buffer {

	Deque<String> deque;

	int maxSize;

	public Buffer(int max) {
		maxSize = max;
		deque = new ArrayDeque<String>();
	}

	Condition empty = new Condition() {

		@Override
		boolean ok() {
			synchronized (deque) {
				return !deque.isEmpty();
			}

		}
	};

	Condition full = new Condition() {

		@Override
		boolean ok() {
			synchronized (deque) {
				return deque.size() < maxSize;
			}

		}
	};

	public void put(String i) {
		full.await();
		synchronized (deque) {
			deque.push(i);
			System.out.println(Thread.currentThread().getName() + " pushing: "
					+ i);
			System.out.println(deque);
		}

		empty.signal();
	}

	public String get() {

		String val;

		empty.await();
		synchronized (deque) {
			val = deque.pollFirst();
			System.out.println(Thread.currentThread().getName() + " peeking: "
					+ val);
			System.out.println(deque);
		}

		full.signal();

		return val;
	}
}